package com.jiangruan.javaproject.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jiangruan.javaproject.Constans;
import com.jiangruan.javaproject.bean.RPCCommon;
import com.jiangruan.javaproject.request.HttpUtils;

import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:SAVA ME(未蒙救赎)
 * @email:1902586238@qq.com
 * @desc:该类用于实现通过访问rpc访问调用bitcoin core的getbestblockhash功能
 * @datetime:2021/12/21 10:43
 **/
public class GetBestBlockHash {
    public RPCCommon getBestBlockHash() {

        //准备rpc请求的以后身份信息，及对应的Base64格式
        String author = Constans.BITCOIN_RPC_USER + ":" + Constans.BITCOIN_RPC_PWD;
        Base64.Encoder encoder = Base64.getEncoder();
        String authorBase64 = encoder.encodeToString(author.getBytes());
        //请求头的属性设置
        Map<String, String> header = new HashMap<>();
        header.put("ContentType", "application/json");
        header.put("Authorization", "Basic " +authorBase64);

        //准备rpc请求数据
        Map<String, Object> body = new HashMap<>();
        body.put("id", 1001);
        body.put("method", "getbestblockhash");
        body.put("params", null);
        body.put("json_rpc", "2.0");
        byte[] bodyBytes = JSONObject.toJSONBytes(body);

        String result = HttpUtils.post(Constans.BITCOIN_RPC_URL, header, bodyBytes);

        //反序列化，拿到result的值
        RPCCommon rpcCommon = JSONObject.parseObject(result, RPCCommon.class);
        return rpcCommon;

    }
}
